using System;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

namespace FreeFlow.Administration
{
	/// <summary>
	/// A collection of procedure versions.
	/// </summary>
	public abstract class VersionCollection : DatabaseAware, IRefreshable, IList, IBindingList, IEnumerable<Version>
	{
    internal List<Version> versionsList;
    internal string procedureName;
    internal int procedureVersion;
    /// <summary>
    /// Initializes a new instance of the <see cref="VersionCollection"/> class for the specified procedure or library.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="procedureName">Name of the procedure or library.</param>
		protected VersionCollection(Server server, string procedureName) : base(server)
		{
      this.procedureName = procedureName;
		}

    /// <summary>
    /// Gets the latest version stored in the database.
    /// </summary>
    /// <value>The latest version.</value>
    public Version LatestVersion
    {
      get
      {
        ReadVersions();
        Version latest = this[0];
        for (int i = 0; i < Count; i++)
        {
          if (this[i].VersionNumber > latest.VersionNumber)
          {
            latest = this[i];
          }
        }
        return latest;
      }
    }

    internal abstract void ReadVersions();

    IEnumerator IEnumerable.GetEnumerator()
    {
      ReadVersions();
      return versionsList.GetEnumerator();
    }

    #region IEnumerable<Version> Members

    /// <summary>
    /// Returns an enumerator that iterates through the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
    /// </returns>
    public IEnumerator<Version> GetEnumerator()
    {
      ReadVersions();
      return versionsList.GetEnumerator();
    }

    #endregion

    internal int count = -1;
    /// <summary>
    /// Gets the number of versions in this collection.
    /// </summary>
    public int Count
    {
      get
      {
        if (versionsList == null)
        {
          if (count == -1)
            ReadCount();
          return count;
        }
        else
          return versionsList.Count;
      }
    }

    internal abstract void ReadCount(); 

    /// <summary>
    /// Gets the <see cref="Version"/> at the specified index.
    /// </summary>
    public Version this[int index]
    {
      get
      {
        ReadVersions();
        return (Version)versionsList[index];
      }
    }

    #region IRefreshable Members

    /// <summary>
    /// Refreshes this instance.
    /// </summary>
    public void Refresh()
    {
      versionsList = null;
      count = -1;
    }

    #endregion
    #region IList Members

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> is read-only.
    /// </summary>
    public bool IsReadOnly
    {
      get
      {
        return true;
      }
    }

    object IList.this[int index]
    {
      get
      {
        ReadVersions();
        if ((index >= 0) && (index < Count))
          return versionsList[index];
        return null;
      }
      set
      {
        throw new NotSupportedException(readOnlyListMessage);
      }
    }

    /// <summary>
    /// Removes the <see cref="T:System.Collections.IList"/>
    /// item at the specified index.
    /// </summary>
    /// <param name="index">The zero-based index of the item to remove.</param>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.IList"/>.</exception>
    /// <exception cref="T:System.NotSupportedException">
    /// 	<para>The <see cref="T:System.Collections.IList"/> is read-only.</para>
    /// 	<para>-or-</para>
    /// 	<para>The <see cref="T:System.Collections.IList"/> has a fixed size.</para>
    /// </exception>
    public void RemoveAt(int index)
    {
      ReadVersions();
      Version version = versionsList[index];
      Remove(version);
    }

    void IList.Insert(int index, object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    void IList.Remove(object value)
    {
      Remove((Version)value);
    }

    /// <summary>
    /// Removes the specified version from the database.
    /// </summary>
    /// <param name="version">The version to remove.</param>
    public void Remove(Version version)
    {
      ReadVersions();
      if (versionsList.Contains(version))
      {
        version.Delete();
        versionsList.Remove(version);
      }
    }

    /// <summary>
    /// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// 	<see langword="true"/> if the <see cref="T:System.Object"/>
    /// is found in the <see cref="T:System.Collections.IList"/>; otherwise, <see langword="false"/>.
    /// </returns>
    public bool Contains(object value)
    {
      ReadVersions();
      return versionsList.Contains((Version)value);
    }

    void IList.Clear()
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Determines the index of a
    /// specific item in the <see cref="T:System.Collections.IList"/>.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// The index of <paramref name="value"/> if found in the list; otherwise, -1.
    /// </returns>
    public int IndexOf(object value)
    {
      ReadVersions();
      return versionsList.IndexOf((Version)value);
    }

    int IList.Add(object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size.
    /// </summary>
    /// <value></value>
    public bool IsFixedSize
    {
      get
      {
        return true;
      }
    }

    #endregion
    #region ICollection Members

    /// <summary>
    /// Gets a value
    /// indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized
    /// (thread-safe).
    /// </summary>
    public bool IsSynchronized
    {
      get
      {
        return false;
      }
    }

    /// <summary>
    /// Copies the elements of
    /// the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
    /// </summary>
    /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
    /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="array"/> is <see langword="null"/>.</exception>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is less than zero.</exception>
    /// <exception cref="T:System.ArgumentException">
    /// 	<para>
    /// 		<paramref name="array"/> is multidimensional.</para>
    /// 	<para>-or-</para>
    /// 	<para>
    /// 		<paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.</para>
    /// 	<para>-or-</para>
    /// 	<para>The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.</para>
    /// </exception>
    /// <exception cref="T:System.InvalidCastException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
    public void CopyTo(Array array, int index)
    {
      ReadVersions();
      versionsList.CopyTo((Version[])array, index);
    }

    /// <summary>
    /// Gets an object that
    /// can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
    /// </summary>
    public object SyncRoot
    {
      get
      {
        return null;
      }
    }

    #endregion
    #region IBindingList Members

    void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
    {
      ReadVersions();
      sortProperty = property;
      sortDirection = direction;
      versionsList.Sort(new Comparer<Version>(sortProperty, sortDirection));
    }

    private PropertyDescriptor sortProperty;
    PropertyDescriptor IBindingList.SortProperty
    {
      get
      {
        return sortProperty;
      }
    }

    bool IBindingList.SupportsSorting
    {
      get
      {
        return true;
      }
    }

    bool IBindingList.IsSorted
    {
      get
      {
        return (sortProperty != null);
      }
    }

    void IBindingList.RemoveSort()
    {
      sortProperty = null;
    }

    private ListSortDirection sortDirection;
    ListSortDirection IBindingList.SortDirection
    {
      get
      {
        return sortDirection;
      }
    }

    #region not implemented 
    int IBindingList.Find(PropertyDescriptor property, object key)
    {
      return 0;
    }

    bool IBindingList.AllowRemove
    {
      get
      {
        return false;
      }
    }

    bool IBindingList.SupportsSearching
    {
      get
      {
        return false;
      }
    }

    private ListChangedEventHandler listChanged;
    event ListChangedEventHandler IBindingList.ListChanged
    {
      add { listChanged += value; }
      remove { listChanged -= value; }

    }

    bool IBindingList.SupportsChangeNotification
    {
      get
      {
        return false;
      }
    }

    object IBindingList.AddNew()
    {
      return null;
    }

    bool IBindingList.AllowEdit
    {
      get
      {
        return false;
      }
    }

    void IBindingList.RemoveIndex(PropertyDescriptor property)
    {
    }

    void IBindingList.AddIndex(PropertyDescriptor property)
    {
    }

    bool IBindingList.AllowNew
    {
      get
      {
        return false;
      }
    }

    #endregion
    #endregion
  }
}
